package com.aurora.leetcode.multithreading;

import java.util.Scanner;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.IntConsumer;

/**
 * @author : qiaodan
 * @date : 2024/9/11 16:54
 * @description 1195. 交替打印字符串
 * 编写一个可以从 1 到 n 输出代表这个数字的字符串的程序，但是：
 * <p>
 * 如果这个数字可以被 3 整除，输出 "fizz"。
 * 如果这个数字可以被 5 整除，输出 "buzz"。
 * 如果这个数字可以同时被 3 和 5 整除，输出 "fizzbuzz"。
 * 例如，当 n = 15，输出： 1, 2, fizz, 4, buzz, fizz, 7, 8, fizz, buzz, 11, fizz, 13, 14, fizzbuzz。
 * <p>
 * 假设有这么一个类：
 * <p>
 * class FizzBuzz {
 * public FizzBuzz(int n) { ... }               // constructor
 * public void fizz(printFizz) { ... }          // only output "fizz"
 * public void buzz(printBuzz) { ... }          // only output "buzz"
 * public void fizzbuzz(printFizzBuzz) { ... }  // only output "fizzbuzz"
 * public void number(printNumber) { ... }      // only output the numbers
 * }
 * 请你实现一个有四个线程的多线程版  FizzBuzz， 同一个 FizzBuzz 实例会被如下四个线程使用：
 * <p>
 * 线程A将调用 fizz() 来判断是否能被 3 整除，如果可以，则输出 fizz。
 * 线程B将调用 buzz() 来判断是否能被 5 整除，如果可以，则输出 buzz。
 * 线程C将调用 fizzbuzz() 来判断是否同时能被 3 和 5 整除，如果可以，则输出 fizzbuzz。
 * 线程D将调用 number() 来实现输出既不能被 3 整除也不能被 5 整除的数字。
 */
public class FizzBuzz_1195 {
    private int n;

    public FizzBuzz_1195(int n) {
        this.n = n;
    }


    /**
     * 我的解法：阻塞队列+atomicInteger
     */

    Lock lock = new ReentrantLock(true);
    Condition condition = lock.newCondition();
    AtomicInteger integer = new AtomicInteger(1);

    public void fizz1(Runnable printFizz) throws InterruptedException {
        while (integer.get() <= n) {
            lock.lock();
            try {
                if (integer.get() > n) break;
                if (integer.get() % 3 == 0 && integer.get() % 5 != 0) {
                    printFizz.run();
                    integer.incrementAndGet();
                    condition.signalAll();
                } else {
                    condition.await();
                }
            } finally {
                lock.unlock();
            }
        }
    }

    // printBuzz.run() outputs "buzz".
    public void buzz1(Runnable printBuzz) throws InterruptedException {
        while (integer.get() <= n) {
            lock.lock();
            try {
                if (integer.get() > n) break;
                if (integer.get() % 5 == 0 && integer.get() % 3 != 0) {
                    printBuzz.run();
                    integer.incrementAndGet();
                    condition.signalAll();
                } else {
                    condition.await();
                }
            } finally {
                lock.unlock();
            }
        }
    }

    // printFizzBuzz.run() outputs "fizzbuzz".
    public void fizzbuzz1(Runnable printFizzBuzz) throws InterruptedException {
        while (integer.get() <= n) {
            lock.lock();
            try {
                if (integer.get() > n) break;
                if (integer.get() % 15 == 0) {
                    printFizzBuzz.run();
                    integer.incrementAndGet();
                    condition.signalAll();
                } else {
                    condition.await();
                }
            } finally {
                lock.unlock();
            }

        }
    }

    // printNumber.accept(x) outputs "x", where x is an integer.
    public void number1(IntConsumer printNumber) throws InterruptedException {
        while (integer.get() <= n) {
            lock.lock();
            try {
                if (integer.get() > n) break;
                if (integer.get() % 3 == 0 || integer.get() % 5 == 0) {
                    condition.signalAll();
                    condition.await();
                } else {
                    printNumber.accept(integer.get());
                    integer.incrementAndGet();
                    condition.signalAll();
                }
            } finally {
                lock.unlock();
            }
        }
    }


    /**
     * 参考实现： CyclicBarrier
     */
    CyclicBarrier cb = new CyclicBarrier(4);

    // printFizz.run() outputs "fizz".
    public void fizz(Runnable printFizz) throws InterruptedException {
        for (int i = 1; i <= n; ++i) {
            if (i % 3 == 0 && i % 5 != 0){
                printFizz.run();
            }
            try{
                cb.await();
            } catch (BrokenBarrierException e) {
                throw new RuntimeException(e);
            }
        }
    }

    // printBuzz.run() outputs "buzz".
    public void buzz(Runnable printBuzz) throws InterruptedException {
        for (int i = 1; i <= n; ++i) {
            if (i % 5 == 0 && i % 3 != 0){
                printBuzz.run();
            }
            try{
                cb.await();
            } catch (BrokenBarrierException e) {
                throw new RuntimeException(e);
            }
        }
    }

    // printFizzBuzz.run() outputs "fizzbuzz".
    public void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {
        for (int i = 1; i <= n; ++i) {
            if (i % 15 == 0){
                printFizzBuzz.run();
            }
            try{
                cb.await();
            } catch (BrokenBarrierException e) {
                throw new RuntimeException(e);
            }
        }
    }

    // printNumber.accept(x) outputs "x", where x is an integer.
    public void number(IntConsumer printNumber) throws InterruptedException {
        for (int i = 1; i <= n; ++i) {
            if (i % 3 != 0 && i % 5 != 0){
                printNumber.accept(i);
            }
            try{
                cb.await();
            } catch (BrokenBarrierException e) {
                throw new RuntimeException(e);
            }

        }
    }

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int i = scan.nextInt();
        FizzBuzz_1195 obj = new FizzBuzz_1195(i);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    obj.fizz(new Runnable() {
                        @Override
                        public void run() {
                            System.out.println("fizz");
                        }
                    });
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    obj.buzz(new Runnable() {
                        @Override
                        public void run() {
                            System.out.println("buzz");
                        }
                    });
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    obj.fizzbuzz(new Runnable() {
                        @Override
                        public void run() {
                            System.out.println("fizzbuzz");
                        }
                    });
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    obj.number(new IntConsumer() {
                        @Override
                        public void accept(int value) {
                            System.out.println(value);
                        }
                    });
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
    }

}
